package com.intretech.umsin.datasource.codemapping.aop;


import com.intretech.umsin.datasource.codemapping.annotations.CodeMappingConfig;
import com.intretech.umsin.datasource.codemapping.annotations.DoMapping;
import com.intretech.umsin.datasource.codemapping.entity.MappingConfig;
import com.intretech.umsin.datasource.codemapping.entity.RootClassInfo;
import com.intretech.umsin.datasource.codemapping.service.CodeMappingService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * @version V1.0
 * @ClassName: DoMappingAOP
 * @Description:
 * @author: 李启联
 * @date: 2020-03-16 10:16
 * @Copyright: Copyright (c), 2020
 */

@Aspect
@Component
public class DoMappingAOP {

    @Autowired
    private CodeMappingService codeMappingService;

    @Around("@annotation(mp)")
    public Object doMapping(ProceedingJoinPoint joinPoint, DoMapping mp) throws Throwable {
        Object result = null;
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        DoMapping doMapping = methodSignature.getMethod().getDeclaredAnnotation(DoMapping.class);
        List<MappingConfig> configs = new LinkedList<>();//new ArrayList<>();//改为链表 保证其按配置顺序执行
        if(doMapping.value().length > 0){
            CodeMappingConfig[] confs = doMapping.value();
            for (CodeMappingConfig config : confs){
                configs.add(new MappingConfig(config.fieldCodeProperty(), config.fieldNameProperty(), config.targetClass(), config.targetClassKeyProperty(), config.targetClassFieldProperty(),config.targetClassName()));
            }
        }

        RootClassInfo rootClassInfo = new RootClassInfo(doMapping.rootClass(),doMapping.rootClassName());
        result = joinPoint.proceed();

        if(null != result && doMapping.doMapping()) {
            codeMappingService.processDoMapping(result, configs,rootClassInfo);
        }

        return result;
    }


}